package com.roytrack.netty.http10_1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * http文件服务器
 * Created by roytrack on 2017-03-17.
 */
public class HttpFileServer {

  private static final String DEFAULT_URL = "/com/roytrack";
  private static final String host = "10.87.156.46";

  public static void main(String[] args) throws InterruptedException {
    int port = 8080;
    if (args.length > 0) {
      try {
        port = Integer.parseInt(args[0]);
      } catch (NumberFormatException e) {
      }

    }
    String url = DEFAULT_URL;
    if (args.length > 1) {
      url = args[1];
    }
    new HttpFileServer().run(port, url);


  }

  public void run(final int port, final String url) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(bossGroup, workerGroup)
              .channel(NioServerSocketChannel.class)
              .handler(new LoggingHandler(LogLevel.INFO))
              .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                  ch.pipeline().addLast("http-decoder", new HttpServerCodec())
                          .addLast("http-aggregator", new HttpObjectAggregator(65536))
                          .addLast("http-chunked", new ChunkedWriteHandler())
                          .addLast("fileServerHandler", new HttpFileServerHandler(url));
                }
              });
      ChannelFuture future = bootstrap.bind(host, port).sync();
      System.out.println("HTTP 文件目录服务器启动 ，网址是" + host + ":" + port + url);
      future.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
}
